package cn.cloud9.opencloud.common.spring.advice;

import cn.cloud9.opencloud.common.annotation.NoResult;
import cn.cloud9.opencloud.common.api.Result;
import org.springframework.core.MethodParameter;
import org.springframework.core.annotation.Order;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.lang.reflect.AnnotatedElement;

/**
 * @author OnCloud9
 * @description
 * @project Open-Cloud
 * @date 2022年04月16日 14:30
 */
@ControllerAdvice(annotations = {RestController.class})
@Order(2)
public class ResultAdvice implements ResponseBodyAdvice<Object> {
    @Override
    public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> aClass) {
        final AnnotatedElement annotatedElement = methodParameter.getAnnotatedElement();
        return annotatedElement.getAnnotation(NoResult.class) == null;
    }

    @Override
    public Object beforeBodyWrite(Object o, MethodParameter methodParameter, MediaType mediaType, Class<? extends HttpMessageConverter<?>> aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
        if (o instanceof Result) return o;
        else if (o instanceof String) {
            // 字符串设置UTF-8编码
            serverHttpResponse.getHeaders().setContentType(MediaType.APPLICATION_JSON_UTF8);
            return Result.getInstance().success(o);
        } else {
            // 其他则直接返回
            return Result.getInstance().success(o);
        }
    }
}
